/**
 * Created with IntelliJ IDEA.
 * User: Hkkkk Guo
 * Date: 2023/2/11
 * Time: 12:03
 * Description:
 */
package com.hangkai.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hangkai.reggie.common.Result;
import com.hangkai.reggie.domain.Category;
import com.hangkai.reggie.domain.Dish;
import com.hangkai.reggie.domain.DishFlavor;
import com.hangkai.reggie.dto.DishDto;
import com.hangkai.reggie.service.CategoryService;
import com.hangkai.reggie.service.DishFlavorService;
import com.hangkai.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    public DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * Dish 页面 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @Transactional
    public Result<Page<DishDto>> dishPage(int page, int pageSize, String name){
        //初始化界面 会执行一次page分页查询 然后筛选会有name
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //添加过滤条件
        lqw.like(null != name, Dish::getName, name);
        lqw.orderByAsc(Dish::getUpdateTime);
        dishService.page(pageInfo, lqw);

        //对象拷贝 //注意 要拷贝的是分页信息 不是里面的对象属性
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> records = pageInfo.getRecords();
        //把records里的dish类 一个个拿出来 放到新的dishDto中 形成新的集合
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        //set records
        dishDtoPage.setRecords(list);
        return Result.success(dishDtoPage);
    }

    /**
     * 根据id获取单个菜品信息 和 口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    //自己试着写
    public Result<DishDto> updateDish(@PathVariable Long id){
        DishDto dishDto = dishService.getByidWithFlavor(id);
        return Result.success(dishDto);
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> addDish(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理所有的菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success("新增菜品成功");
    }

    /**
     * 修改菜品提交
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> updateDish(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        //清理所有的菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success("修改菜品成功");
    }

    /**
     * 批量或单个删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> deleteDish(@RequestParam List<Long> ids){
        dishService.removeByIds(ids);
        //清理所有的菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success("删除成功");
    }

    /**
//     * 批量或单个修改菜品状态 （停售、起售）
     */
    @PostMapping("/status/{status}")
    public Result<String> unSoldDishs(@PathVariable int status, @RequestParam List<Long> ids){
        //清理所有的菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        for(Long id : ids){
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return Result.success("修改商品状态成功");
    }

    /**
     * 添加套餐时 根据类别显示菜品列表
     * @param categoryId
     * @param status
     * @return
     */
//    @GetMapping("/list")
//    public Result<List<Dish>> getDishList(Long categoryId, Integer status){
//        //条件构造器
//        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//        //根据categoryId查询得到菜品列表
//        lqw.eq(categoryId != null, Dish::getCategoryId, categoryId);
//        lqw.eq(status!= null, Dish::getStatus, status);
//        //查询起售状态的菜品
//        lqw.eq(Dish::getStatus, 1);
//        //排序条件
//        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> dishList = dishService.list(lqw);
//        return Result.success(dishList);
//    }
    @GetMapping("/list")
    public Result<List<DishDto>> getDishList(Long categoryId, Integer status){
        List<DishDto> dishDtoList = null;
        //动态构造key
        String key = "dish_" + categoryId + "_" + status;
        //从Redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //如果存在 直接返回 无需查询数据库
        if(dishDtoList != null){
            return Result.success(dishDtoList);
        }

        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //根据categoryId查询得到菜品列表
        lqw.eq(categoryId != null, Dish::getCategoryId, categoryId);
        lqw.eq(status!= null, Dish::getStatus, status);
        //查询起售状态的菜品
        lqw.eq(Dish::getStatus, 1);
        //排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(lqw);

        LambdaQueryWrapper<DishFlavor> lqw_flavor = new LambdaQueryWrapper<>();
        dishDtoList = dishList.stream().map((item) -> {
            //新造一个DishDto对象 把Dish对象的数据复制过来
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //每次清空条件构造器
            lqw_flavor.clear();
            Long id = item.getId();
            //根据菜品id来查询口味
            lqw_flavor.eq(DishFlavor::getDishId, id);
            List<DishFlavor> flavors = dishFlavorService.list(lqw_flavor);
            //把口味列表赋值给DishDto
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());
        //如果Redis不存在缓存 需要查询数据库 将查询到的菜品缓存到Redis
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return Result.success(dishDtoList);
    }
}
